<script setup>
import {
  userRegisterService,
  userlogin,
  userRegistercode,
  userFogetpassword
} from '/src/api/user.js'
import { User, Lock, Phone, Key } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '/src/stores/modules/user'
const isRegister = ref(false)
const isFoget = ref(false)
const totalSecond = ref(60)
const second = ref(60)
const timer = ref(null)
const totalSecond2 = ref(60)
const second2 = ref(60)
const timer2 = ref(null)
const router = useRouter()
const options = [
  { value: '男', label: '我是男生' },
  { value: '女', label: '我是女生' },
  { value: '未知', label: '这是私密' }
]
const form = ref()
// 整个用于提交的注册的form数据对象
const formModel = ref({
  name: '',
  username: '',
  password: '',
  newPassword: '',
  sexs: '',
  idCard: '',
  email: '',
  phone: '',
  code: ''
})
//正则校验 pattern: 正则规则  \S 非空字符
//自定义校验 => 写逻辑校验，校验函数
//{ validator: (rule, value, callback) => {} }
// (1) rule 当前校验规则的相关信息
// (2) value 所校验的表单元素目前的表单值
// (3) callback 无论成功还是失败，都需要callback
//   - callback() 校验成功
//   - callback(new Error(错误信息)) 校检失败
const rules = {
  name: [
    { required: true, message: '请输入昵称', trigger: 'change' }
    //{ min: 5, max: 10, message: '用户名必须是5-10位字符', trigger: 'blur' } // blur失去焦点
  ],
  username: [{ required: true, message: '请输入用户名', trigger: 'change' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    {
      pattern: /^\S{1,15}$/,
      message: '密码必须是1—15位的非空字符',
      trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    {
      pattern: /^\S{1,15}$/,
      message: '密码必须是1—15位的非空字符',
      trigger: 'blur'
    }
  ],
  sexs: [
    { required: true, message: '请输入性别', trigger: 'change' }
    // {
    //   validator: (rule, value, callback) => {
    //     if (value === '男' || value === '女') {
    //       callback()
    //     } else {
    //       callback(new Error('请输入男或女'))
    //     }
    //   },
    //   trigger: 'change'
    // }
  ],
  idCard: [{ required: true, message: '请输入学号', trigger: 'change' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '邮箱格式不正确',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'change' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '电话格式不正确',
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
}
const register = async () => {
  //注册成功之前，先进行校验，校验成功发请求，失败进行提示
  await form.value.validate()
  const res = await userRegisterService(formModel.value)
  console.log(res)
  if (res.code == 1) {
    ElMessage.success('注册成功,请登录')
    isRegister.value = false
  } else {
    ElMessage.error(res.msg)
  }
}
const userStore = useUserStore()
const login = async () => {
  await form.value.validate()
  const res = await userlogin(formModel.value)
  console.log(res)
  if (res.code == 1) {
    ElMessage.success('登录成功')
    userStore.setToken(res.data.token)
    router.push('/')
  } else {
    ElMessage.error(res.msg)
  }
  // console.log(error)
}

const getcode = async () => {
  await form.value.validateField(['email'])
  // ElMessage.success('发送成功')
  if (!timer.value && second.value === totalSecond.value) {
    timer.value = setInterval(() => {
      second.value--
      if (second.value < 1) {
        clearInterval(timer.value)
        timer.value = null
        second.value = totalSecond.value
      }
    }, 1000)
    const res = await userRegistercode(formModel.value)
    if (res.code == 1) {
      ElMessage.success(res.data)
    } else {
      ElMessage.error(res.data)
    }
  }
}
const getcode2 = async () => {
  await form.value.validateField(['email'])
  // ElMessage.success('发送成功')
  if (!timer2.value && second2.value === totalSecond2.value) {
    timer2.value = setInterval(() => {
      second2.value--
      if (second2.value < 1) {
        clearInterval(timer2.value)
        timer2.value = null
        second2.value = totalSecond2.value
      }
    }, 1000)
    const res = await userRegistercode(formModel.value)
    if (res.code == 1) {
      ElMessage.success(res.data)
    } else {
      ElMessage.error(res.data)
    }
  }
}
//alert('邮箱未输入！')
const fogetpassword = async () => {
  await form.value.validate()
  const res = await userFogetpassword(formModel.value)
  Element.success(res.msg)
}
//切换的时候，重置表单内容
watch(isRegister, isFoget, () => {
  formModel.value = {
    name: '',
    username: '',
    password: '',
    newPassword: '',
    sexs: '',
    idCard: '',
    email: '',
    phone: '',
    code: ''
  }
})
</script>

<template>
  <!--1.结构 
       el-row 表示一行,一行分成24份 
       (1) el-col表示列  :span="12" 一行中占12份 (50%) :prefix-icon icon图标
       (2) :span="6" 一行中占6份 (25%) :offset="3" 一行中左侧margin份数

       el-form 表单组件
       el-form-item 表单的一行 (表单域)
       el-input 表单元素 (输入框)
  -->
  <!-- 2.校验
       (1) el-form => :model="ruleForm" 绑定的整个form的数据对象 {xxx, xxx, xxx }
       (2) el-form => :rules="rules"    绑定的整个rules规则对象  {xxx, xxx, xxx }
       (3) 表单元素 => v-model="ruleForm.xxx" 给表单元素，绑定form的子属性 双向绑定数据
       (4) el-form-item => prop配置生效的是哪个校验规则 (和rules中的字段要对应)
  -->
  <el-row class="login-page">
    <el-col :span="15" class="bg"><h1>邀奇难平二手平台</h1></el-col>
    <!-- 背景图片 -->
    <el-col :span="6" :offset="2" class="form">
      <!-- 注册表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister && isFoget == false"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item>
          <el-scrollbar height="200px" class="scroll">
            <el-form-item prop="name" class="form-item-with-spacing">
              <el-input
                v-model="formModel.name"
                :prefix-icon="User"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
            <el-form-item prop="username" class="form-item-with-spacing">
              <el-input
                v-model="formModel.username"
                :prefix-icon="User"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" class="form-item-with-spacing">
              <el-input
                show-password
                v-model="formModel.password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
            <el-form-item prop="sexs" class="form-item-with-spacing">
              <el-select
                v-model="formModel.sexs"
                placeholder="请选择性别"
                size="large"
                style="width: 100%"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="idCard" class="form-item-with-spacing">
              <el-input
                v-model="formModel.idCard"
                :prefix-icon="Key"
                placeholder="请输入学号"
              ></el-input>
            </el-form-item>
            <el-form-item prop="email" class="form-item-with-spacing">
              <el-input
                v-model="formModel.email"
                :prefix-icon="Lock"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone" class="form-item-with-spacing">
              <el-input
                v-model="formModel.phone"
                :prefix-icon="Phone"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code" class="form-item-with-spacing">
              <el-input
                v-model="formModel.code"
                :prefix-icon="Lock"
                style="width: 75%"
                placeholder="请输入验证码"
              ></el-input
              ><el-button @click="getcode" type="primary" style="width: 25%">{{
                second == totalSecond ? '发送' : second + 'S'
              }}</el-button>
            </el-form-item>
          </el-scrollbar>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else-if="isRegister == false && isFoget == false"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link
              type="primary"
              @click="isFoget = true"
              :underline="false"
              color="blcak"
              >忘记密码？</el-link
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isFoget"
      >
        <el-form-item>
          <h1>忘记密码</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email" class="form-item-with-spacing">
          <el-input
            v-model="formModel.email"
            :prefix-icon="Lock"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" class="form-item-with-spacing">
          <el-input
            v-model="formModel.code"
            :prefix-icon="Lock"
            style="width: 75%"
            placeholder="请输入验证码"
          ></el-input
          ><el-button @click="getcode2" type="primary" style="width: 25%">{{
            second2 === totalSecond2 ? '发送' : second2 + 'S'
          }}</el-button>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="formModel.newPassword"
            name="newPassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <el-link
            type="info"
            :underline="false"
            @click="(isRegister = false), (isFoget = false)"
          >
            ← 返回
          </el-link>
          <el-button
            @click="fogetpassword"
            class="button"
            type="primary"
            auto-insert-space
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: white;
  .bg {
    background:
      url() no-repeat 60% center / 240px auto,
      url('/src/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    background-image: url('/src/assets/yoroshiku.png');
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
  h1 {
    margin: auto;
  }
  .scroll {
    width: 100%;
  }
  .form-item-with-spacing {
    margin-bottom: 18px; /* 你可以根据需要调整这个值 */
  }
}
</style>
